#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include "mrf49xa.h"

void send_packet(int fp, mrf_packet *packet)
{
    int L_i;

    printf("tx : ");
    for (L_i = 0; L_i < packet->length; L_i++) printf("%02X ", *(((uint8_t*)packet)+L_i));
    printf("\n");
    write(fp, (uint8_t*)packet, packet->length);
}

int main(int argc, char **argv)
{
    int L_i;
    int L_len;
    int fp;
    mrf_packet packet;
    
    fp = open("/dev/mrf49xa", O_RDWR);

    /* Wait 300ms for mrf49xa driver initialization */
    usleep(300000);
        
    /* Send a 4 bytes packet */
    packet.length = 4; // length MUST be multiple of 4. It includes its own 1-byte length
    packet.payload[0] = 1;
    packet.payload[1] = 1;
    packet.payload[2] = 1;
    send_packet(fp, &packet);

    while(1)
    {
        /* Poll every 20ms */
        usleep(20000);
        if ( read(fp, &packet, sizeof(mrf_packet))  > 1)
        {
            /* MRF49XA received a packet */
            printf("RX : ");
            L_len = packet.length;
            for (L_i = 0; L_i < L_len-1; L_i++)
            {
                printf("%02X ", packet.payload[L_i]);
            }
            printf("\n");
        }
    }

    return 0;
}
